package com.nebula.api.config;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.util.Objects;

/**
 * jacksonUtils
 *
 * @author Eastern unbeaten
 * @version 1.0
 * @date 2019/6/27 22:30
 * @mail chenshiyun2011@163.com
 */
public class JacksonUtils {

    private static final JacksonUtils JACKSONUTILS = new JacksonUtils();

    ObjectMapper mapper;

    private JacksonUtils() {
        this.mapper = (ObjectMapper) ApplicationContextHelper.getBean("objectMapper");
        if (Objects.isNull(mapper)) {
            //错误
        }
    }

    public static final JacksonUtils create() {
        return JACKSONUTILS;
    }


    public String toJsonStr(Object obj) {
        try {
            return mapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return "";
    }

    public <T> T toClass(String content, Class<T> valueType) {
        try {
            return mapper.readValue(content, valueType);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}
